package com.study.rabbitmq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

public class RabbitMqUtil {

    //配置文件相对路径
    private static String path = "application.properties";
    private static Integer port = 5672;
    private static String host = "localhost";
    private static String username = "guest";
    private static String password  = "guest";

    public static void setPort(Integer port) {
        RabbitMqUtil.port = port;
    }

    public static void setHost(String host) {
        RabbitMqUtil.host = host;
    }

    public static void setUsername(String username) {
        RabbitMqUtil.username = username;
    }

    public static void setPassword(String password) {
        RabbitMqUtil.password = password;
    }

    /**
     * 获取信道
     * @return
     */
    public static Channel getChannel(){
        ConnectionFactory factory = new ConnectionFactory();
        setParams();
        System.out.println(port+"/"+host+"/"+username+"/"+password);
        factory.setPort(port);
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);
        try {
            Connection connection =  factory.newConnection();
            Channel channel = connection.createChannel();
            return channel;
        } catch (IOException e) {
            System.out.println("连接失败！");
            throw  new RuntimeException(e);
        } catch (TimeoutException e) {
            System.out.println("连接超时！");
            throw new RuntimeException(e);
        }
    }

    /**
     * 加载配置文件
     * @return
     * @throws FileNotFoundException
     */
    public static void setParams() {
        try(InputStream inputStream = RabbitMqUtil.class.getClassLoader().getResourceAsStream(path)){
            Properties properties = new Properties();
            properties.load(inputStream);

            Integer port  = Integer.getInteger(""+properties.get("port")) ;
            if (port!=null)
                setPort(port);
            String  host  = (String) properties.get("host");
            if (host!=null&&!host.isEmpty())
                setHost(host);
            String username  = (String) properties.get("username");
            if (username!=null&&!username.isEmpty())
                setUsername(username);
            String password = (String) properties.get("password");
            if (password!=null&&!password.isEmpty())
                setPassword(password);

        } catch (IOException e) {
            System.out.println("配置文件加载失败");
            throw new RuntimeException(e);
        }
    }

}
